package org.example.tails.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.tails.util.JwtUtil;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns="/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("TokenFilter init");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri=request.getRequestURI();
        if(uri.contains("/login")){
            log.info("TokenFilter doFilter: uri={}",uri);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token=request.getHeader("token");
        if(token==null||token.isEmpty()){
            log.info("TokenFilter doFilter: token is null");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try{
            JwtUtil.parseToken(token);
        }catch(Exception e){
            log.info("TokenFilter doFilter: token is invalid");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        log.info("TokenFilter doFilter: token is valid");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        log.info("TokenFilter destroy");
        Filter.super.destroy();
    }
}
